// 销售订单自定义状态管理
frappe.provide("upsystem.sales_order_custom_status");

upsystem.sales_order_custom_status = {
    init: function() {
        this.bind_events();
        this.enhance_status_field();
        this.control_field_editability();
    },
    
    // 页面加载完成后初始化
    onload: function() {
        var me = this;
        // 延迟执行，确保DOM完全加载
        setTimeout(function() {
            me.init();
            me.hide_shopify_fields();
        }, 1000);
    },
    
    bind_events: function() {
        // 监听状态字段变化
        $(document).on('change', '[data-fieldname="status"]', function() {
            upsystem.sales_order_custom_status.handle_status_change($(this).val());
        });
    },
    
    enhance_status_field: function() {
        // 直接修改状态字段选项
        this.add_custom_status_options();
    },
    
    add_custom_status_options: function() {
        var me = this;
        // 等待状态字段加载
        var checkField = function() {
            var status_field = $('[data-fieldname="status"]');
            if (status_field.length > 0) {
                me.update_status_options(status_field);
            } else {
                // 如果字段还没加载，继续等待
                setTimeout(checkField, 500);
            }
        };
        checkField();
    },
    
    update_status_options: function(status_field) {
        // 检查是否已经添加了自定义状态
        var current_html = status_field.html();
        if (current_html.indexOf('To Manufacturing') === -1) {
            // 添加自定义状态选项
            var custom_options = '<option value="To Manufacturing">To Manufacturing</option>' +
                                '<option value="To Shipment">To Shipment</option>';
            
            // 在现有选项后添加自定义选项
            status_field.append(custom_options);
            
            // 添加状态指示器样式
            this.add_status_indicators();
            
            console.log("✅ 已添加自定义状态选项: To Manufacturing, To Shipment");
        }
    },
    
    add_status_indicators: function() {
        // 添加自定义状态的CSS样式
        if (!$('#custom-status-styles').length) {
            var styles = `
                <style id="custom-status-styles">
                .status-indicator[data-status="To Manufacturing"] {
                    background-color: #6f42c1 !important;
                    color: white !important;
                }
                .status-indicator[data-status="To Shipment"] {
                    background-color: #20c997 !important;
                    color: white !important;
                }
                </style>
            `;
            $('head').append(styles);
        }
    },
    
    handle_status_change: function(new_status) {
        // 处理状态变更
        if (this.is_custom_status(new_status)) {
            this.show_custom_status_form(new_status);
        }
        // 控制字段编辑权限
        this.control_field_editability();
    },

    hide_shopify_fields: function() {
        if (!cur_frm) {
            return;
        }

        const fields_to_hide = [
            "customer",
            "order_type",
            "tax_category",
            "shipping_rule",
            "incoterm",
            "taxes_and_charges",
            "apply_discount_on",
            "additional_discount_percentage",
            "discount_amount"
        ];

        fields_to_hide.forEach(fieldname => {
            try {
                cur_frm.toggle_display(fieldname, false);
            } catch (e) {
                console.warn("Failed to hide field", fieldname, e);
            }
        });

        const sections_to_hide = [
            "taxes_section",
            "additional_discount_section"
        ];
        sections_to_hide.forEach(sec => {
            const field = cur_frm.get_field(sec);
            if (field && field.wrapper) {
                field.wrapper.hide();
            }
        });

        const tables_to_hide = [
            "sales_taxes_and_charges"
        ];
        tables_to_hide.forEach(table_field => {
            const field = cur_frm.get_field(table_field);
            if (field && field.grid && field.grid.wrapper) {
                field.grid.wrapper.hide();
            }
        });
    },
    
    is_custom_status: function(status) {
        // 判断是否为自定义状态
        const custom_statuses = ["To Manufacturing", "To Shipment"];
        return custom_statuses.includes(status);
    },
    
    control_field_editability: function() {
        var me = this;
        var current_status = frappe.get_route()[1]; // 获取当前销售订单ID
        if (!current_status) return;
        
        // 获取当前状态
        var status_field = $('[data-fieldname="status"]');
        if (!status_field.length) return;
        
        var status = status_field.val();
        
        // 无论什么状态，都保持所有字段可编辑
        this.enable_all_fields();
        
        // 如果是自定义状态，显示状态提示信息
        if (this.is_custom_status(status)) {
            this.show_custom_status_notice(status);
        } else {
            // 隐藏自定义状态提示
            $('.custom-status-notice').remove();
        }
    },
    
    show_custom_status_notice: function(status) {
        // 移除现有提示
        $('.custom-status-notice').remove();
        
        var status_info = {
            "To Manufacturing": {
                title: "待生产状态",
                description: "订单已确认，准备进入生产阶段。所有字段都可以编辑。",
                color: "#6f42c1"
            },
            "To Shipment": {
                title: "待发货状态", 
                description: "生产完成，准备发货。所有字段都可以编辑。",
                color: "#20c997"
            }
        };
        
        var info = status_info[status];
        if (info) {
            // 创建状态提示信息
            var notice = $('<div class="custom-status-notice alert" style="margin: 10px 0; background-color: ' + info.color + '; color: white; border: none;">' +
                '<strong>' + info.title + '：</strong>' + info.description +
                '</div>');
            
            // 插入到表单顶部
            $('.form-section:first').before(notice);
        }
    },
    
    
    enable_all_fields: function() {
        var me = this;
        
        // 启用所有表单字段
        $('.form-section input, .form-section select, .form-section textarea').each(function() {
            var field = $(this);
            field.prop('readonly', false);
            field.prop('disabled', false);
            field.removeClass('read-only');
        });
        
        // 启用所有链接字段
        $('.form-section [data-fieldname]').each(function() {
            var field = $(this);
            field.prop('readonly', false);
            field.prop('disabled', false);
            field.removeClass('read-only');
        });
        
        console.log("✅ 已启用所有字段编辑");
    },
    
    
    show_custom_status_form: function(status) {
        // 显示自定义状态提示信息
        this.show_custom_status_notice(status);
    },
    
};

// 页面加载完成后自动初始化
$(document).ready(function() {
    upsystem.sales_order_custom_status.onload();
});

// 监听页面路由变化
$(document).on('page-change', function() {
    upsystem.sales_order_custom_status.onload();
});